Vue.component('upload-images', {
    template: `<el-upload class="upload-demo" :show-file-list="false" accept="image/*" drag :on-change="upload" :auto-upload="false" action="" multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
            只能上传jpg/png文件，且不超过500kb
            <el-slider style="width:350px" :min="1" v-model="quality" :format-tooltip="formatTooltip"></el-slider>
            <div v-show="quality < 100">当前图片压缩至{{quality}}%</div>
        </div>
    </el-upload>
    `,
    props: ['data'],
    data() {
        return {
            quality: 100,
        }
    },
    methods: {
        formatTooltip(val) {
            return '图片压缩比例：' + val + '%';
        },
        upload({ raw }) {
            const that = this;
            new Compressor(raw, {
                quality: that.quality / 100,
                success(file) {
                    const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
                    const isLt500K = file.size / 1024 / 1024 < 0.5; // 500KB  
                    if (!isJPGorPNG) {
                        that.$message({
                            message: '上传头像图片只能是 JPG/PNG 格式!',
                            type: 'warning'
                        })
                        return false;
                    }
                    // if (!isLt500K) {
                    //     that.$message({
                    //         message: '上传图片大小不能超过 500KB! 可压缩后上传',
                    //         type: 'warning'
                    //     })
                    //     return false;
                    // }
                    const formData = new FormData();
                    formData.append('file', file, file.name);
                    let oFileReader = new FileReader();
                    oFileReader.readAsDataURL(file);
                    oFileReader.onload = function (e) {
                        that.data.push({
                            Base64: e.target.result,
                            DataLength: file.size,
                            FileName: file.name
                        })
                    }
                },
            });
        }
    }
})
new Vue({
    el: '#app',
    data() {
        return {
            fileList: [],
            tableData: [],
            form: {
                page: 1,
                limit: 15,
            },
            loading: false,
            success: 0,
            error: 0,
            prop: {},//类型
            image: [],
            brand: [],
            category: [],
            series: [],
            item: [],
            unit: [],
            classify: [],
            update: true,
            defaultProps: {
                children: 'Children',
                label: 'Classify_Name',
                value: 'Classify_Name',
                multiple: true,
            }
        }
    },
    mixins:[importMixin],
    mounted() {
        this.getData();
    },
    methods: {
        submitImage() {
            const that = this;
            if (this.image.length > 0) {
                this.loading = true;
                $.ajax({
                    headers: requestHeaders('JSON'),
                    url: `${BASE_URL2}/article/articlePictureUpLoad`,
                    type: 'POST',
                    data: JSON.stringify(this.image),
                    complete: function (XMLHttpRequest) {
                        that.loading = false;
                        requestPretreatment(XMLHttpRequest);
                    },
                    success: function (Result) {
                        if (Result.Status = "success") {
                            that.$message({
                                message: '上传成功！',
                                type: 'success'
                            })
                            that.update = false;
                            that.update = true;
                        }
                    },
                    dataType: "json"
                });
            } else {
                this.$message({
                    message: '请先导入图片后再上传',
                    type: 'warning'
                })
            }
        },
        handleImgClick(formName) {//点击查看图片
            this.$refs[formName][0].showViewer = true;
        },
        RemoveImage(index) {//删除图片
            this.image.splice(index, 1);
        },
        getData() {
            const that = this;
            const Condition = "Row_Status='0'";
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_brand',
                    Condition,
                },
                success: function (res) {
                    that.brand = res;
                },
                error: function () {
                    that.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_category',
                    Condition,
                },
                success: function (res) {
                    that.category = res;
                },
                error: function () {
                    that.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_series',
                    Condition,
                },
                success: function (res) {
                    that.series = res;
                },
                error: function () {
                    that.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_item',
                    Condition,
                },
                success: function (res) {
                    that.item = res;
                },
                error: function () {
                    that.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
                type: 'POST',
                data: {
                    Data: 'business_article_unit',
                    Condition,
                },
                success: function (res) {
                    that.unit = res;
                },
                error: function () {
                    that.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/getAllClassify`,
                type: 'GET',
                success: function (data) {
                    that.classify = data
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            });
        },
        submitUpload(i = 0) {
            if (i < this.tableData.length) {
                this.loading = true;
                if (!this.tableData[i].Article_Name) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '商品名称不能为空'
                    this.error++;
                    this.submitUpload(i + 1);
                } else if (!this.tableData[i].Article_Code) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '规格编号不能为空'
                    this.error++;
                    this.submitUpload(i + 1);
                } else if (!this.tableData[i].Brand_Name) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '品牌不能为空'
                    this.error++;
                    this.submitUpload(i + 1);
                } else if (!this.tableData[i].Brand_Name||!this.brand.some(j=>j.Brand_Name == this.tableData[i].Brand_Name)) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '该品牌不存在，请先录入'
                    this.error++;
                    this.submitUpload(i + 1);
                } else if (!this.tableData[i].Category_Name||!this.category.some(j=>j.Category_Name == this.tableData[i].Category_Name)) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '该类别不存在，请先录入'
                    this.error++;
                    this.submitUpload(i + 1);
                // } 
                // else if (!this.tableData[i].Series_Name||!this.series.some(j=>j.Series_Name == this.tableData[i].Series_Name)) {
                //     this.tableData[i].isStatus = '2';
                //     this.tableData[i].Cause = '该系列不存在，请先录入'
                //     this.error++;
                //     this.submitUpload(i + 1);
                // } else if (!this.tableData[i].Item_Name||!this.item.some(j=>j.Item_Name == this.tableData[i].Item_Name)) {
                //     this.tableData[i].isStatus = '2';
                //     this.tableData[i].Cause = '该款型不存在，请先录入'
                //     this.error++;
                //     this.submitUpload(i + 1);
                } else if (this.tableData[i].Unit_Price == '') {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '统一吊牌价不能为空'
                    this.error++;
                    this.submitUpload(i + 1);
                } else if (this.tableData[i].Children.business_article_specifications.some(i=>i.Specifications_Name=='')) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '规格名称不能为空'
                    this.error++;
                    this.submitUpload(i + 1);
                } else if (this.tableData[i].Children.business_article_specifications.some(i=>i.Unit_Price=='')) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '规格吊牌价不能为空'
                    this.error++;
                    this.submitUpload(i + 1);
                } else if (this.tableData[i].Children.business_article_specifications.some(i=>i.SKU_Quantity=='')) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = 'SKU数量不能为空'
                    this.error++;
                    this.submitUpload(i + 1);
                } else if (this.tableData[i].Children.business_article_specifications.some(j=>!j.Unit)) {
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '规格中单位不能为空'
                    this.error++;
                    this.submitUpload(i + 1);
                } else if (this.tableData[i].Children.business_article_specifications.some(j=>!j.Unit||!this.unit.some(x=>x.Unit == j.Unit))) {
                    console.log(this.tableData[i].Children.business_article_specifications[0].Unit);
                    this.tableData[i].isStatus = '2';
                    this.tableData[i].Cause = '该商品规则中单位不存在，请先录入'
                    this.error++;
                    this.submitUpload(i + 1);
                } else {
                    this.tableData[i].Brand_SerialNumber = this.brand.filter(j=>j.Brand_Name == this.tableData[i].Brand_Name)[0].Brand_SerialNumber;
                    this.tableData[i].Category_SerialNumber = this.category.filter(j=>j.Category_Name == this.tableData[i].Category_Name)[0].Category_SerialNumber;
                    if (this.series.some(j=>j.Series_Name == this.tableData[i].Series_Name)) {
                        this.tableData[i].Series_SerialNumber = this.series.filter(j=>j.Series_Name == this.tableData[i].Series_Name)[0].Series_SerialNumber;
                    }
                    if (this.item.some(j=>j.Item_Name == this.tableData[i].Item_Name)) {
                        this.tableData[i].Item_SerialNumber = this.item.filter(j=>j.Item_Name == this.tableData[i].Item_Name)[0].Item_SerialNumber;
                    }
                    this.tableData[i].Children.business_article_specifications.forEach(j=>{
                        j.Weight_Unit = this.unit.filter(x=>x.Unit == j.Unit)[0].Article_Unit_SerialNumber;
                    })
                    this.submitForm({ Data: JSON.stringify({ Add: { business_article_info: [this.tableData[i]], business_article_config: [{ Article_Code: this.tableData[i].Article_Code }] } }) }, (res) => {
                        if (res.Status == 'success') {
                            this.tableData[i].isStatus = '1';
                            this.tableData[i].Cause = '',
                            this.success++;
                        } else {
                            this.tableData[i].isStatus = '2';
                            this.error++;
                            this.tableData[i].Cause = '该商品编号已存在'
                        }
                        this.submitUpload(i + 1);
                    })
                }
            } else if (i != 0) {
                this.loading = false;
                this.$message.success("批量导入结束")
            } else {
                this.$message({
                    message: '请先导入模板后再上传',
                    type: 'warning'
                })
            }
        },
        submitForm(data, callback) {
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalSave`,
                type: 'POST',
                data,
                success: function (res) {
                    callback(res)
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        },
        handleChange({ raw }) {//导入监听文件
            const that = this;
            var reader = new FileReader();
            reader.readAsBinaryString(raw);
            reader.onload = function (e) {
                var data = e.target.result;
                var wb = XLSX.read(data, {
                    type: 'binary' //以二进制的方式读取
                });
                var sheet = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
                var sheet1 = wb.Sheets[wb.SheetNames[1]];//sheet1代表excel表格中的第二页
                var sheet2 = wb.Sheets[wb.SheetNames[2]];//sheet2代表excel表格中的第三页
                var image = XLSX.utils.sheet_to_json(sheet1);//利用接口实现转换。
                var classify = XLSX.utils.sheet_to_json(sheet2);//利用接口实现转换。
                var json = XLSX.utils.sheet_to_json(sheet);//利用接口实现转换。
                let arr = [];
                try {
                    json.forEach(item => {
                        item.isEdit = false;
                        item.isStatus = '0'
                        //1.判断数组用有无该商品
                        if (arr.some(i => i.Article_Code == item['商品编号'])) {//老商品
                            arr.filter(i => i.Article_Code ==  item['商品编号'])[0].Children.business_article_specifications.push({
                                Article_Specifications_SerialNumber: '',//规格主键
                                Article_SerialNumber: '',
                                Specifications_Name: item['规格名称'],//规格名称
                                Unit_Price: item['吊牌价'],//吊牌价
                                SKU_Quantity: item['SKU数量'],//SKU数量
                                Picture_URL: item['规格图片'],//规格图片
                                Weight: item['SKU重量'],//重量
                                Size: item['SKU尺寸'],
                                Weight_Unit: item['SKU单位'],//单位      
                                JDCOM_Unit_Price: item['规格京东价'],//吊牌价
                                JDCOM_URL: item['规格京东链接'],//京东路径
                                Package_Quantity: item['小包装数量'],//包装数量
                                SKU_Package_Size: item['包装尺寸'],//包装尺寸
                                Carton_Quantity: item['大包装数量'],//大包装数量
                                Children_Specifications_SerialNumber: '',
                                isEdit: false,
                            })
                        } else {//新商品
                            //图片
                            let business_article_pic = [], business_article_classify = [], Classify = [];
                            if (image.some(i => i['商品编号'] == item['商品编号'])) {//判断有无图片
                                //取出来，形成结构
                                image.filter(i => i['商品编号'] == item['商品编号']).forEach(item => {
                                    if (item['图片名称']&&item['图片名称'].includes(item['商品编号'])) {
                                        business_article_pic.push({
                                            Article_PicNumber: '',
                                            Article_SerialNumber: '',
                                            Picture_Type: item['图片类型'],
                                            Picture_Order: item['图片类型'] == '0' ? business_article_pic.filter(i => i.Picture_Type == '0').length + 1 : business_article_pic.filter(i => i.Picture_Type == '1').length + 1,
                                            Picture_URL: item['图片名称'].trim()
                                        })
                                    }
                                })
                            }
                            //分类汇总有没有
                            if (classify.some(i => i['商品编号']== item['商品编号'])) {
                                classify.filter(i => i['商品编号'] == item['商品编号']).forEach(item => {
                                    Classify.push(item['分类汇总'].split('/'));
                                })
                            }
                            arr.push({
                                Article_SerialNumber: '',//商品主键
                                Article_Name: item['商品名称'],//商品名称
                                Article_Code: item['商品编号'],
                                Picture_URL: item['封面图片']&&item['封面图片'].includes(item['商品编号'])?item['封面图片']:'',//规格图片
                                Brand_Name: item['品牌'],//
                                Category_Name: item['类别'],//商品类别
                                Series_Name: item['系列'],//商品系列
                                Item_Name: item['款型'],//商品款型
                                Unit_Price: item['吊牌价'],//吊牌价
                                Unify_Unit_Price: '0',
                                ClassifyJSON: JSON.stringify(Classify),
                                Classify,
                                JDCOM_Unit_Price: item['商品京东价'],
                                JDCOM_URL:item['商品京东链接'],
                                isEdit: false,
                                isStatus: '0',
                                Cause:'',
                                Children: {
                                    business_article_specifications: [{
                                        Article_Specifications_SerialNumber: '',//规格主键
                                        Article_SerialNumber: '',
                                        Specifications_Name: (item['规格名称'].trim()+''),//规格名称
                                        Unit_Price: item['吊牌价'],//吊牌价
                                        SKU_Quantity: item['SKU数量'],//SKU数量
                                        Picture_URL: item['规格图片']&&item['规格图片'].includes(item['商品编号'])?item['规格图片']:'',//规格图片
                                        Weight: item['SKU重量'],//重量
                                        Size: item['SKU尺寸'],
                                        Unit:item['SKU单位'],//单位      
                                        JDCOM_Unit_Price: item['规格京东价'],//吊牌价
                                        JDCOM_URL: item['规格京东链接'],//京东路径
                                        Package_Quantity: item['小包装数量'],//包装数量
                                        SKU_Package_Size: item['包装尺寸'],//包装尺寸
                                        Carton_Quantity: item['大包装数量'],//大包装数量
                                        Children_Specifications_SerialNumber: '',
                                        isEdit: false,
                                    }],
                                    business_article_pic,
                                    business_article_classify
                                }
                            })
    
                        }
                    });
                } catch (error) {
                    that.$message({
                        message: '导入模板信息有误',
                        type: 'warning'
                    })
                }
                that.tableData = arr
            }
        },
        handleSizeChange(val) {
            this.form.page = 1;
            this.form.limit = val;
        },
        handleCurrentChange(val) {
            this.form.page = val;
        },
        handleEdit(row) {//修改当前行
            row.isEdit = !row.isEdit
        },
        handleRemove(index) {//移除当前行
            this.$confirm('是否要删除此行?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.tableData = this.tableData.filter((i, id) => id != (this.form.page - 1) * this.form.limit + index)
            }).catch(() => { });
        },
        handleClean() {//清空
            this.$confirm('是否要清空导入数据?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.tableData = []
            }).catch(() => { });
        },
    },
})